import {
    AfterViewInit,
    ChangeDetectorRef,
    Component,
    ElementRef,
    Inject,
    Injector,
    OnDestroy,
    OnInit,
    ViewChild
} from '@angular/core';
import {ControlUIWidget, SFComponent, SFItemComponent} from '@delon/form';
import {UploadFile} from 'ng-zorro-antd';
import {Observable} from 'rxjs';
import {UploadChangeParam, UploadXHRArgs} from 'ng-zorro-antd/upload/interface';
import Viewer from 'viewerjs';
import {SysAttachmentUploadSchema} from './sys-attachment-upload-schema';
import {SysAttachment} from '../entity/sys-attachment';
import {BaseAttachmentService} from '../service/base-attachment.service';
import {SysAttachmentService} from '../service/sys-attachment.service';

@Component({
    selector: 'sys-attachment-upload',
    templateUrl: './sys-attachment-upload-alain.component.html',
    styleUrls: ['./sys-attachment-upload-alain.component.less']
})
export class SysAttachmentUploadAlainComponent extends ControlUIWidget<SysAttachmentUploadSchema> implements OnInit, AfterViewInit, OnDestroy {
    /* 用于注册小部件 KEY 值 */
    static readonly KEY = 'sys-attachment-upload';
    res: any;
    fileList: UploadFile[] = [];
    gallery: Viewer;

    @ViewChild('attachmentList', {static: true})
    attachmentListContainer: ElementRef<HTMLElement>;

    private baseAttachmentService: BaseAttachmentService;

    constructor(
        @Inject(ChangeDetectorRef) public readonly cd: ChangeDetectorRef,
        @Inject(Injector) public readonly injector: Injector,
        @Inject(SFItemComponent) public readonly sfItemComp?: SFItemComponent,
        @Inject(SFComponent) public readonly sfComp?: SFComponent) {
        super(cd, injector, sfItemComp, sfComp);
    }

    ngOnInit(): void {
        this.baseAttachmentService = this.baseAttachmentService || this.ui.baseAttachmentService || this.injector.get(SysAttachmentService);
        this.ui.baseAttachmentParam = this.ui.baseAttachmentParam || {};
        // const res: any = {
        //     type: 'select',
        //     text: this.ui.text || '点击上传',
        //     action: `${environment.baseServerUrl}/sys/attachment/upload`,
        //     accept: this.ui.accept || '',
        //     directory: false,
        //     openFileDialogOnClick: true,
        //     limit: this.ui.limit == null ? 0 : +this.ui.limit,
        //     filter: this.ui.filter == null ? [] : this.ui.filter,
        //     size: this.ui.fileSize == null ? 0 : +this.ui.fileSize,
        //     fileType: this.ui.fileType || '',
        //     listType: this.ui.listType || 'text',
        //     multiple: true,
        //     name: 'file',
        //     showUploadList: this.ui.showUploadList == null ? true : this.ui.showUploadList,
        //     withCredentials: true,
        //     resReName: ['message', 'id'],
        //     urlReName: ['message', 'readAddress'],
        //     beforeUpload: null,
        //     limitFileCount: 999
        // };
        if (this.ui) {
            this.ui.filter = this.ui.filter == null ? [] : this.ui.filter;
        }
        // if (res.listType === 'picture-card') {
        //     this.btnType = 'plus';
        // }
        // this.res = res;
        //
    }


    ngAfterViewInit() {
        // this.gallery = new Viewer(this.attachmentListContainer.nativeElement, {
        //     title: () => '附件查看',
        // });
        // if (this.gallery) {
        //     this.gallery.hide();
        // }
    }

    ngOnDestroy(): void {
        if (this.gallery) {
            this.gallery.destroy();
        }
    }


    reset(_value: any): void {
        if (_value) {
            const fileList = [] as UploadFile[];
            const ids = _value.split(',');
            this.baseAttachmentService.getAttachments(ids, this.ui.baseAttachmentParam).subscribe(
                res => {
                    if (res.success) {
                        for (const file of res.message) {
                            if (file) {
                                fileList.push(this.convertToUploadFile(file));
                            }
                        }
                    }
                    this.fileList = fileList;
                    this.cd.detectChanges();
                    if (this.gallery) {
                        this.gallery.update();
                    }
                    this.setValue(_value);
                }
            );
        }
    }

    change(param: UploadChangeParam) {
        if (this.ui.change) {
            this.ui.change(param);
        }
        if (param.type === 'success') {
            this.cd.detectChanges();
            if (this.gallery) {
                this.gallery.update();
            }
            const values = this.getValueStr();
            this.setValue(values);
        }
    }

    getValueStr(): string {
        const values = [];
        for (let j = 0; j < this.fileList.length; j++) {
            const file = this.fileList[j];
            values.push(file.response.id);
        }
        return values.join(',');
    }

    customRequest(item: UploadXHRArgs) {
        const formData = new FormData();
        formData.append('file', item.file as any);
        return this.baseAttachmentService.uploadAttachment(formData, this.ui.baseAttachmentParam).subscribe(
            result => {
                if (result.success) {
                    const sysAttachment = result.message;
                    const uploadFile = this.convertToUploadFile(sysAttachment);
                    uploadFile.size = item.file.size;
                    if (!uploadFile.type) {
                        uploadFile.type = item.file.type;
                    }
                    item.onSuccess(sysAttachment, uploadFile, result);
                }
            }
        );
    }

    customRemove(file: UploadFile): boolean | Observable<boolean> {
        return new Observable<boolean>(
            (subscriber) => {
                subscriber.next(true);
                subscriber.complete();
                this.cd.detectChanges();
                if (this.gallery) {
                    this.gallery.update();
                }
                this.setValue(this.getValueStr());
            }
        );
    }

    handlePreview(file: UploadFile) {
        if (!file || !file.response) {
            return;
        }
        if (file.response.picture) {
            if (this.gallery) {
                this.gallery.view(0);
                this.gallery.show();
            }
        } else {
            window.open(file.url);
        }
    }

    convertToUploadFile(sysAttachment: SysAttachment): UploadFile {
        const obj = {
            uid: sysAttachment.id,
            size: 0,
            name: sysAttachment.fileName,
            type: sysAttachment.type,
            url: this.baseAttachmentService.getReadAttachmentUrl(sysAttachment.id, this.ui.baseAttachmentParam),
            // this.ui.customReadUrl ? `${this.ui.customReadUrl}/${sysAttachment.id}` : `${this.sysAttachmentService.url}/read/${sysAttachment.id}`,
            response: sysAttachment,
            percent: 100,
            status: 'success',
            message: '上传成功'
        } as UploadFile;
        if (sysAttachment.picture) {
            obj.thumbUrl = this.baseAttachmentService.getReadAttachmentThumbUrl(sysAttachment.id, this.ui.baseAttachmentParam);
        } else {
            obj.thumbUrl = '';
        }
        return obj;
    }
}
